package com.example.fang.demodruid.swing;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @describe:
 * @author:01410843
 * @Date 2022/6/21 12:29
 **/
public class CodePicture {

    /**
     * 缓存信息
     */
    public static Map<String, String> cache = new ConcurrentHashMap<String, String>();

    // 验证码字符集
    private static final char[] chars = ("0123456789abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
    // 字符数量
    private static final int SIZE = 4;
    // ⼲扰线数量
    private static final int LINES = 10;
    // 宽度
    private static final int WIDTH = 80;
    // ⾼度
    private static final int HEIGHT = 30;
    // 字体⼤⼩
    private static final int FONT_SIZE = 30;



    static {
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        executor.scheduleAtFixedRate(() -> {
            System.out.println("我执行了");
        }, 0, 10, TimeUnit.SECONDS);
    }

    /**
     * @Author 01410843
     * @Description 生成随机码及图片
     * @Date 12:30 2022/6/21
     * @Param []
     * @return java.lang.Object[]
     **/
    public static Object[] createImage(){
        StringBuffer sb = new StringBuffer();
        // 1.创建空⽩图⽚
        BufferedImage image = new BufferedImage(
                WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        // 2.获取图⽚画笔
        Graphics graphic = image.getGraphics();
        // 3.设置画笔颜⾊
        graphic.setColor(Color.LIGHT_GRAY);
        // 4.绘制矩形背景
        graphic.fillRect(0, 0, WIDTH, HEIGHT);
        // 5.画随机字符
        Random ran = new Random();
        for (int i = 0; i <SIZE; i++) {
            // 取随机字符索引
            int n = ran.nextInt(chars.length);
            // 设置随机颜⾊
            graphic.setColor(getRandomColor());
            // 设置字体⼤⼩
            graphic.setFont(new Font(
                    null, Font.BOLD + Font.ITALIC, FONT_SIZE));
            // 画字符
            graphic.drawString(
                    chars[n] + "", i * WIDTH / SIZE, HEIGHT/2+10);
            // 记录字符
            sb.append(chars[n]);
        }
        System.out.println(sb.toString());
        //将验证码放入本地缓存中
        cache.put("code",sb.toString());
        // 6.画⼲扰线
        for (int i = 0; i < LINES; i++) {
            // 设置随机颜⾊
            graphic.setColor(getRandomColor());
            // 随机画线
            graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT),
                    ran.nextInt(WIDTH), ran.nextInt(HEIGHT));
        }
        // 7.返回验证码和图⽚
        return new Object[]{sb.toString(), image};
    }

    public static Color getRandomColor() {
        Random ran = new Random();
        Color color = new Color(ran.nextInt(256),
        ran.nextInt(256), ran.nextInt(256));
        return color;
    }
    //测试输出
    public static void main(String[] args) throws IOException {
        JPanel panel=new JPanel();
        CodePicture index = new CodePicture();
        // 创建 JFrame 实例
        JFrame frame = new JFrame("顺手付支付-天威测试证书生成器");
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        frame.setBounds((screenSize.width/2-250), (screenSize.height/2-170), 500, 340);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel);
        /*
         * 调用用户定义的方法并添加组件到面板
         */
        index.placeComponents(panel,frame);
        // 设置界面可见
        frame.setVisible(true);

    }


    //添加图⽚，获取验证码
    public void getPicture(JLabel label,JPanel panel){
        Object[] obj = CodePicture.createImage();
        String code = obj[0].toString();
        //从缓存中获取code
        System.out.println("缓存中获取到的code:"+cache.get("code"));
        ImageIcon img = new ImageIcon((BufferedImage)obj[1]);//创建图⽚对象
        label.setIcon((Icon)img);
        panel.add(label);

    }

    private void placeComponents(JPanel panel,final JFrame frame){
        /* 布局部分我们这边不多做介绍
         * 这边设置布局为 null
         */
        panel.setLayout(null);

        Font font = new Font("Microsoft Yahei", Font.PLAIN, 14);

        // 创建 JLabel
        JLabel userLabel = new JLabel("商户号：");
        userLabel.setBounds(20,40,100,30);
        userLabel.setFont(font);
        panel.add(userLabel);
        final JTextField userText = new JTextField(20);
        userText.setBounds(120,40,200,30);
        panel.add(userText);

        //创建验证码
        JLabel codeLabel = new JLabel("输入验证码：");
        codeLabel.setBounds(20,80,100,30);
        codeLabel.setFont(font);
        panel.add(codeLabel);

        final JTextField codeText = new JTextField(20);
        codeText.setBounds(120,80,200,30);
        panel.add(codeText);

        JLabel label = new JLabel();
        ImageIcon img = new ImageIcon((BufferedImage)CodePicture.createImage()[1]);
        label.setIcon((Icon)img);
        label.setBounds(340,80,WIDTH,HEIGHT);
        panel.add(label);

        label.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e){
                if(e.getClickCount() == 1){
                    //重新获取验证码
                    getPicture(label,panel);
                }
            }
        });
    }


}
